package com.wechat.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fhMall.request.AddMemberCouponRequest;
import com.fhMall.response.UmsMemberResponse;
import com.wechat.core.constant.Constant;
import com.wechat.feign.FeignBaseService;
import com.wechat.feign.FhEmalMemberApi;
import com.wechat.feign.FhEmalllCouponApi;
import com.wechat.models.request.LoginRequest;
import com.wechat.models.response.FeignResult;
import com.wechat.models.response.WxLoginResponse;
import com.wechat.service.user.WechatUserService;
import com.wechat.util.JwtTokenUtil;
import io.jsonwebtoken.impl.DefaultClaims;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;

import javax.servlet.http.HttpServletRequest;


/**
 *  impl
 *
 * @author 
 * @date 2019-09-18 20:00:31
 */
@Service
public class WechatUserServiceImpl implements WechatUserService, FeignBaseService {

    @Value("${spring.redis.tokenTimeout}")
    private int timeout;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private FhEmalMemberApi fhEmalMemberApi;
    @Autowired
    private FhEmalllCouponApi fhEmalllCouponApi;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 微信登录
     * @param loginRequest
     * @return
     */
    @Override
    public WxLoginResponse wxLogin(LoginRequest loginRequest)  {
        boolean isRegister = true;
//        wxMpService.getUserService().userInfo("");
        WxLoginResponse response = new WxLoginResponse();
        String openId = loginRequest.getOpenid();

        //查询用户信息
        String result = fhEmalMemberApi.queryMemberByOpenId(openId);
        UmsMemberResponse umsMember = toResponse(result, new TypeReference<FeignResult<UmsMemberResponse>>() {});
        if (umsMember == null) {
            isRegister = false;
            umsMember = new UmsMemberResponse();
            if(loginRequest.getPrePartnerId()!=null){
                umsMember.setPrePartnerId(loginRequest.getPrePartnerId());
                umsMember.setPartnerType(2);
            }else{
                umsMember.setPartnerType(0);
            }
            umsMember.setSourceType(1);
            umsMember.setHasBuyGood(0);
            umsMember.setHistoryIntegration(0);
            umsMember.setCurrentIntegration(0);
            umsMember.setConsumption(0D);
            umsMember.setStatus(1);
            umsMember.setThirdAccount(loginRequest.getOpenid());
            umsMember.setSex(loginRequest.getSex());
            try {
                WxMpUser wxMpUser=wxMpService.getUserService().userInfo(loginRequest.getOpenid());
                umsMember.setHeadPic(wxMpUser.getHeadImgUrl());
                umsMember.setNickname(wxMpUser.getNickname());
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            //保存用户信息
            String saveResult = fhEmalMemberApi.saveMember((JSONObject)JSONObject.toJSON(umsMember));
            umsMember = toResponse(saveResult, new TypeReference<FeignResult<UmsMemberResponse>>() {});
        }

        //赠送优惠券
        if (!isRegister){
            fhEmalllCouponApi.addMemberCoupon(AddMemberCouponRequest.builder().memberId(umsMember.getId()).couponTemplatType(3).build());
        }

        DefaultClaims claims = new DefaultClaims();
        claims.setAudience(umsMember.getThirdAccount());
        String token = jwtTokenUtil.generateToken(umsMember.getId().toString(), claims);
        redisTemplate.opsForValue().set(Constant.WECHAT_USER_ID + umsMember.getId(), JSONObject.toJSONString(umsMember), timeout);

        response.setOpenId(umsMember.getThirdAccount());
        response.setToken(token);
        response.setIfFocus(umsMember.getHasFocusWechat());
        response.setMemberId(umsMember.getId().toString());
        return response;
    }



}
